package com.io.commonlib.helper

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.view.WindowManager
import android.widget.Toast

object ToastHelper {
    private var mToast: Toast? = null
    private val mHandler = Handler(Looper.getMainLooper())
    private const val THREAD_MAIN = "main"

    /**
     * 显示toast(可以子线程中使用Toast)-short
     *
     * @param msg Toast消息
     */
    @SuppressLint("ShowToast")
    fun showShortToast(context: Context?, msg: String?) {
        try {
            // 判断是在子线程，还是主线程
            if (THREAD_MAIN == Thread.currentThread().name) {
                if (mToast == null) {
                    mToast = Toast.makeText(context, msg, Toast.LENGTH_SHORT)
                } else {
                    mToast!!.cancel()
                    mToast = Toast.makeText(context, msg, Toast.LENGTH_SHORT)
                    mToast?.setText(msg)
                }
                mToast?.show()
            } else {
                mHandler.post { Toast.makeText(context, msg, Toast.LENGTH_LONG).show() }
            }
        } catch (e: WindowManager.BadTokenException) {
            e.printStackTrace()
            //android API25系统BUG,TOAST异常
        }
    }


    /**
     * 显示toast(可以子线程中使用Toast)-short
     *
     * @param msg Toast消息
     */
    @SuppressLint("ShowToast")
    fun showLongToast(context: Context?, msg: String?) {
        try {
            // 判断是在子线程，还是主线程
            if (THREAD_MAIN == Thread.currentThread().name) {
                if (mToast == null) {
                    mToast = Toast.makeText(context, msg, Toast.LENGTH_LONG)
                } else {
                    mToast?.cancel()
                    mToast = Toast.makeText(context, msg, Toast.LENGTH_LONG)
                    mToast?.setText(msg)
                }
                mToast?.show()
            } else {
                // 子线程
                mHandler.post { Toast.makeText(context, msg, Toast.LENGTH_LONG).show() }
            }
        } catch (e: WindowManager.BadTokenException) {
            e.printStackTrace()
            //android API25系统BUG,TOAST异常
        }
    }

    fun cancelToast(){
        mToast?.let {
            mToast?.cancel()
            mToast = null
        }
    }
}